function Rewriter(site)
{
	this.site=site;
	this.init();
}

Rewriter.prototype.init=function() {
	this.rewrites=this.site.sql.execute_and_fetch("rewrites/list");
	for (var i=0;i<this.rewrites.length;i++) {
		var r=this.rewrites[i];
		if (r.fields!=null) r.fields=r.fields.split(/,/);
		r.regexp=new RegExp(r.regexp);
	}
}

Rewriter.prototype.work=function(space) {
//	space.action_src=space.action;
	if (space.action==null) throw new Error("action==null!");
	for (var i=0;i<this.rewrites.length;i++) {
		var r=this.rewrites[i];
		var arr;
		if (!(arr=space.action.match(r.regexp))) continue;
		space.std_rewrite=true;
		space.std_rewrite_fields={};
		var k=1;
		if (r.fields!=null) {
			for (var j=0;j<r.fields.length;j++) {
				space.fields[r.fields[j]]=arr[k];k++;
				space.std_rewrite_fields[r.fields[j]]=1;
			}
		}
		if (r.controller_name) {
			var arr=r.controller_name.match(/^(\w+)(?:|\((.+)\))$/);
			var href;
			if (arr[2]!=undefined) eval("href="+arr[2]);
			space.action=space.controllers[arr[1]](space,href,r);
			return;
		}
		if (r.alias) {
			space.action=r.alias;
			return;
		}
		throw new Error("Misconfigured rewrite");
	}
}

exports.rewriter=Rewriter;
